﻿// Models/ExamDbContext.cs
using System.Data.Entity;

namespace WebApplication1.Models
{
    public class ExamDbContext : DbContext
    {
        public ExamDbContext() : base("name=ExamDbConnection")
        {
        }

        public DbSet<PracticeSession> PracticeSessions { get; set; }
        public DbSet<PracticeAnswer> PracticeAnswers { get; set; }

        public DbSet<User> Users { get; set; }
        public DbSet<Exam> Exams { get; set; }
        public DbSet<Question> Questions { get; set; }
        public DbSet<Option> Options { get; set; }
        public DbSet<ExamResult> ExamResults { get; set; }
        public DbSet<UserAnswer> UserAnswers { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // 配置 UserAnswer 的外键约束，避免循环级联删除
            modelBuilder.Entity<UserAnswer>()
                .HasRequired(ua => ua.ExamResult)
                .WithMany(er => er.UserAnswers)
                .HasForeignKey(ua => ua.ResultId)
                .WillCascadeOnDelete(false); // 禁用级联删除

            modelBuilder.Entity<UserAnswer>()
                .HasRequired(ua => ua.Question)
                .WithMany(q => q.UserAnswers)
                .HasForeignKey(ua => ua.QuestionId)
                .WillCascadeOnDelete(false); // 禁用级联删除

            // 配置 ExamResult 的外键约束
            modelBuilder.Entity<ExamResult>()
                .HasRequired(er => er.User)
                .WithMany()
                .HasForeignKey(er => er.UserId)
                .WillCascadeOnDelete(false); // 禁用级联删除

            modelBuilder.Entity<ExamResult>()
                .HasRequired(er => er.Exam)
                .WithMany(e => e.ExamResults)
                .HasForeignKey(er => er.ExamId)
                .WillCascadeOnDelete(false); // 禁用级联删除

            // 配置 Question 的外键约束
            modelBuilder.Entity<Question>()
                .HasRequired(q => q.Exam)
                .WithMany(e => e.Questions)
                .HasForeignKey(q => q.ExamId)
                .WillCascadeOnDelete(false); // 禁用级联删除

            // 配置 Option 的外键约束
            modelBuilder.Entity<Option>()
                .HasRequired(o => o.Question)
                .WithMany(q => q.Options)
                .HasForeignKey(o => o.QuestionId)
                .WillCascadeOnDelete(false); // 禁用级联删除

            base.OnModelCreating(modelBuilder);
        }
    }
}